using namespace std;

#include <string.h>
#include <fstream>
#include <list>
#include "Indice.h"
#include "Arbol.h"
#include "RegistroArbol.h"

int IndexadoBSharp::buscar(Indice* indice, list<string> key) {
	cout << "Buscando en BSharp" << endl;

	Arbol tree;
	for (unsigned int i = 0; i < key.size(); i++) {
		string filePath = indice->Indice::getNombreArch();
		cout << "entre"<<endl;

		stringstream out;
		out << i;
		filePath.append(out.str());
		tree.Abrir((char*)filePath.c_str());
		for (list<string>::iterator it = key.begin(); it != key.end(); it++) {
			RegistroArbol* registro = tree.ObtenerRegistro(&(*it));
			if (registro != NULL) {
				return(registro->offset);
			}
		}
	}
	cout << "No encontro nada" << endl;
	throw 1;
}

void IndexadoBSharp::indexar(Indice* indice, list<string> key, int offset){
	RegistroArbol registro;
	registro.offset = offset;
	list<string>::iterator it = key.begin();

	while(it != key.end()){
		string filePath = indice->getNombreArch();
		Arbol tree;
		stringstream out;
		//out << i;
		filePath.append(out.str());
		fstream* destino = NULL;
		char* path = new char[strlen(filePath.c_str())];
		strcpy(path, filePath.c_str());
		destino->open(path, ios::out | ios::in | ios::binary);
		if (!destino->eof()) {
			tree.Abrir(path);
			tree.InsertarRegistro(&(*it), &registro);
		} else {
			tree.Crear(path);
			tree.InsertarRegistro(&(*it), &registro);
		}
		it++;
	}
}

int IndexadoBSharp::eliminar(Indice* indice, list<string> key){

	list<string>::iterator it = key.begin();
	while(it != key.end()){
		string filePath = indice->getNombreArch();
		Arbol tree;
		stringstream out;
		filePath.append(out.str());
		fstream* destino = NULL;
		char* path = new char[strlen(filePath.c_str())];
		strcpy(path, filePath.c_str());
		destino->open(path, ios::out | ios::in | ios::binary);
		if (!destino->eof()) {
			tree.Abrir(path);
			bool deleted = tree.Eliminar(&(*it));
			if (deleted) {
				cout << "Se eliminó correctamente el registro." << endl;
			} else {
				cout << "No existe el registro: " << (*it) << endl;
				throw 1;
			}
		} else {
			cout << "No existe el archivo: " << filePath << endl;
			throw 1;
		}
		it++;
	}
	throw 1;
}
